/**
 * Created by cjk on 16/3/2.
 */
Date.prototype.format = function (format) {
  var o = {
    'M+': this.getMonth() + 1, //month
    'd+': this.getDate(), //day
    'h+': this.getHours(), //hour
    'm+': this.getMinutes(), //minute
    's+': this.getSeconds(), //second
    'q+': Math.floor((this.getMonth() + 3) / 3), //quarter
    'S': this.getMilliseconds() //millisecond
  }

  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  }

  for (var k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    }
  }
  return format;
}
var RRSCalendar = {
  me: null,
  options: null,
  currentDate: null,
  titleContainer: null,
  tableContainer: null,
  preButton: null,
  nextButton: null,
  onDateClick: null,
  init: function (options) {
    me = this;
    this.options = options || {};
    this.currentDate = new Date(); //当前Date;
    this.titleContainer = document.getElementById(this.options.titleContainerId);
    this.tableContainer = document.getElementById(this.options.tableContainerId);
    this.preButton = document.getElementById(this.options.preButtonId);
    this.nextButton = document.getElementById(this.options.nextButtonId);
    this.preButton.addEventListener('click', me.preMonth);
    this.nextButton.addEventListener('click', me.nextMonth);
    this.onDateClick = options.onDateClick;
    this.titleContainer.innerText = this.currentDate.format('yyyy-MM-dd');
    this.refresh();
  },
  addMonth: function (month) {
    me.currentDate.setMonth(me.currentDate.getMonth() + month);
  },
  preMonth: function () {
    me.addMonth(-1);
    me.refresh();
  },
  nextMonth: function () {
    me.addMonth(1);
    me.refresh();
  },
  /**
   * 是否为闰年
   * @param year
   * @returns {number}
   */
  isLeap: function (year) {
    return (year % 100 == 0 ? res = (year % 400 == 0 ? 1 : 0) : res = (year % 4 == 0 ? 1 : 0));
  },
  refresh: function () {
    me.titleContainer.innerText = me.currentDate.format('yyyy-MM-dd');
    var ynow = me.currentDate.getFullYear(); //年份
    var mnow = me.currentDate.getMonth(); //月份
    var dnow = me.currentDate.getDate(); //今日日期
    var n1str = new Date(ynow, mnow, 1); //当月第一天Date资讯
    var firstday = n1str.getDay(); //当月第一天星期几
    var firstWeek = me.getWeek(n1str);
    var m_days = new Array(31, 28 + me.isLeap(ynow), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); //各月份的总天数

    var tr_str = Math.ceil((m_days[mnow] + firstday - 1) / 7); //表格所需要行数
    var innerHTML = '';

    //打印表格第一行（有星期标志）
    innerHTML = innerHTML + '<div class="table">' +
      '<div class="table-header-group">' +
      '<div class="table-row">' +
      '<div class="table-cell">周</div>' +
      '<div class="table-cell">一</div>' +
      '<div class="table-cell">二</div>' +
      '<div class="table-cell">三</div>' +
      '<div class="table-cell">四</div>' +
      '<div class="table-cell">五</div>' +
      '<div class="table-cell">六</div>' +
      '<div class="table-cell">日</div>' +
      '</div>' +
      '</div>' +
      '<div class="table-row-group">';//表格内容开始
    for (i = 0; i < tr_str; i++) { //表格的行
      innerHTML = innerHTML + '<div class="table-row">';
      for (k = 0; k < 8; k++) { //表格每行的单元格
        if (k == 0) {
          var week = firstWeek + i;
          innerHTML = innerHTML + '<div class="table-cell weeks">' +
            '<div class="week-text">' + week + '</div>' +
            '<div class="agenda">3</div>' +
            '</div>';
        } else {
          idx = i * 7 + k; //单元格自然序列号
          var dx = idx - firstday; //计算日期
          //过滤无效日期（小于等于零的、大于月总天数的）
          var date = me.addDate(n1str, dx);
          date_str = date.getDate();
          var dateStr = date.format("yyyy-MM-dd");
          //打印日期：今天底色为红
          if (me.isToday(date)) {
            innerHTML = innerHTML + '<div class="table-cell today-bg" id="' + dateStr + '" ng-click="" onclick=me.onDateClick("' + dateStr + '")>' +
              '<div class="day-text">' + date_str + '</div>' +
              '<div class="agenda">3</div>' +
              '</div>';
          } else if (dx < 0 || dx >= m_days[mnow]) {
            // 不属于本月
            innerHTML = innerHTML + '<div class="table-cell" id="' + dateStr + '" ng-click="" onclick=me.onDateClick("' + dateStr + '")>' +
              '<div class="day-text-gray">' + date_str + '</div>' +
              '<div class="agenda">5</div>' +
              '</div>';
          } else {
            innerHTML = innerHTML + '<div class="table-cell" id="' + dateStr + '" ng-click="" onclick=me.onDateClick("' + dateStr + '")>' +
              '<div class="day-text">' + date_str + '</div>' +
              '<div class="agenda">5</div>' +
              '</div>';

          }
        }
      }
      innerHTML = innerHTML + '</div>'; //表格的行结束
    }
    innerHTML = innerHTML + '</div>'; //表格内容结束
    innerHTML = innerHTML + '</div>'; //表格结束
    me.tableContainer.innerHTML = innerHTML;
  },
  isToday: function (d) {
    var now = new Date();
    if (d.getDate() != now.getDate()) {
      return false;
    }
    if (d.getMonth() != now.getMonth()) {
      return false;
    }
    if (d.getFullYear() != now.getFullYear()) {
      return false;
    }
    return true;
  },
  addDate: function (date, day) {
    date = date.valueOf();
    date = date + day * 24 * 60 * 60 * 1000
    date = new Date(date);
    return date;
  },


  getWeek: function (date) {
    var fDate = new Date();
    fDate.setFullYear(date.getFullYear());
    fDate.setMonth(0);
    fDate.setDate(1);
    var rq = date - fDate;
    var s1 = Math.ceil(rq / (24 * 60 * 60 * 1000)) + 1;
    // 第一天是星期几
    var fweek = fDate.getDay();
    if (fweek == 0) {
      fweek = 7;
    }
    var yu = s1 - (7 - fweek + 1);
    var weekno = Math.ceil(yu / 7) + 1;
    console.log('今天是本年第' + s1 + '天，第' + weekno + '周');
    return weekno
  }
};
